<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { Plus } from '@element-plus/icons-vue'
import { onBeforeUnmount, ref, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import { pushKnowledgeAPI } from '@/apis/knowledge'

let mode = 'default'

// 编辑器实例
const editorRef = shallowRef()

// 内容 HTML
let valueHtml = ref('')

const toolbarConfig = {
    excludeKeys: [
        'todo',
        'emotion',
        'insertImage',
        'group-video',
        'codeBlock',
        'fullScreen',
    ],
}
const editorConfig = { 
    placeholder: '请输入内容...',
    MENU_CONF: {
        uploadImage: {
            server: 'http://127.0.0.1:8081/upload', // 上传接口
            fieldName: 'file', 
            maxFileSize: 1024 * 1024 * 10, // 限制文件大小
            allowedFileTypes: ['image/*'], // 限制文件类型
            timeout: 5 * 1000, // 超时时间

            customInsert(res, insertFn) {
                if (res.code === 2000) {
                    // console.log(res)
                    insertFn(res.data, '', res.data)
                    return
                }
                ElMessage({ type: 'error', message: '图片上传失败，请重试' })
            }
        }
    }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

const handleCreated = (editor) => {
    editorRef.value = editor // 记录 editor 实例，重要！
}

// 封面上传
let imageUrl = ref('')

const handleCoverSuccess = (response, uploadFile) => {
    // console.log(response)
    // console.log(uploadFile);
    // imageUrl.value = URL.createObjectURL(uploadFile.raw)
    imageUrl.value = response.data
}

const beforeCoverUpload = (file) => {
    // console.log(file.type)
    if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        ElMessage({
            type: 'error',
            message: '图片上传格式仅支持 JPEG、JPG、PNG'
        })
        return false
    } else if (file.size / 1024 / 1024 > 10) {
        ElMessage.error('图片大小不要超过 10MB')
        return false
    }
    return true
}

// 返回
const router = useRouter()
const back = () => {
    router.replace('/userCenter/knowledge')
}

// 发布文章
let title = ref('请输入标题')
const push = async () => {
    // console.log(title.value) // 标题
    // console.log(editorRef.value.getHtml()) // 内容
    // console.log(imageUrl.value) // 封面
    if (check()) {
        const res = await pushKnowledgeAPI({ 
            title: title.value,
            pic: imageUrl.value,
            content: editorRef.value.getHtml()
        })
        if (res.code === 2000) {
            ElMessage({ type: 'success', message: '知识发布成功' })
            back()
        }
    }
}

const check = () => {
    if (editorRef.value.getHtml() === '<p><br></p>') {
        ElMessage({ type: 'warning', message: '知识内容不能为空' })
        return false
    } else if (title.value === '' || title.value === '请输入标题') {
        ElMessage({ type: 'warning', message: '请输入一个标题' })
        return false
    } else if (imageUrl.value === '') {
        ElMessage({ type: 'warning', message: '请上传一张知识封面' })
        return false
    }
    return true
}
</script>

<template>
<div class="editor-page">
    <div class="fix-box">
        <div id="top-container">
            <div class="top-wrapper">
                <div class="wrapper-l">
                    <a href="#" class="back" @click="back">
                        <img src="@/assets/icon/back.png" alt="">
                        <div>返回</div>
                    </a>
                    <div style="font-weight: bold; font-size: 18px;">写知识</div>
                </div>
                <div class="wrapper-r">
                    <a href="#" class="push-btn" @click="push">发布知识</a>
                </div>
            </div>
        </div>
        <div class="toolbar-container">
            <Toolbar
                id="editor-toolbar"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                :mode="mode"
            />
        </div>
    </div>
    <div class="content-container">
        <div id="title-container">
            <input type="text" v-model="title">
        </div>
        <Editor
            id="editor-container"
            v-model="valueHtml"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
        />
        <div id="setup-container">
            <div style="font-size: 18px;">发布设置</div>
            <div class="upload-area">
                <div>添加封面</div>
                <el-upload
                    class="cover-uploader"
                    action="http://127.0.0.1:8081/upload"
                    :show-file-list="false"
                    :on-success="handleCoverSuccess"
                    :before-upload="beforeCoverUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="cover-uploader-icon"><Plus /></el-icon>
                    <template #tip>
                        <div class="el-upload__tip">图片上传格式支持 JPEG、JPG、PNG</div>
                    </template>
                </el-upload>
            </div>
        </div>
    </div>
</div>
</template>

<style scoped lang='scss'>
.editor-page {
    overflow: hidden;

    .fix-box {
        position: fixed;
        width: 100%;
        z-index: 99;
    }

    #top-container {
        height: 61px;
        width: 100%;
        border-bottom: 1px solid #ccc;
        background-color: #fff;

        .top-wrapper {
            display: flex;
            justify-content: space-between;
            align-items: center;
            width: 1000px;
            height: 100%;
            margin: 0 auto;

            .wrapper-l {
                display: flex;
                justify-content: space-between;
                align-items: center;
                height: 100%;

                .back {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    font-size: 20px;;
                    padding-right: 15px;
                    margin-right: 15px;
                    border-right: 1px solid #ccc;

                    $imgSize: 30px;
                    img {
                        width: $imgSize;
                        height: $imgSize;
                    }
                }   
            }

            .wrapper-r {
                display: flex;
                align-items: center;

                .push-btn {
                    display: block;
                    height: 35px;
                    color: #fff;
                    font-size: 14px;
                    background-color: #39bf3e;
                    padding: 0 20px;
                    margin-right: 20px;
                    text-align: center;
                    line-height: 35px;
                    border-radius: 4px;
                }
            }
        }
    }

    .toolbar-container {
        width: 100%;
        border-bottom: 1px solid #ccc;
        background-color: #fff;

        #editor-toolbar {
            width: 1280px;
            margin: 0 auto;
        }
    }

    .content-container {
        position: relative;
        width: 850px;
        margin: 150px auto 50px auto;
        padding: 20px 50px 50px 50px;
        border: 1px solid #e8e8e8;
        box-shadow: 0 2px 10px rgb(0 0 0 / 12%);
        background-color: #fff;

        #title-container {
            padding: 20px 0;
            border-bottom: 1px solid #e8e8e8;

            input {
                font-size: 30px;
                border: 0;
                outline: none;
                width: 100%;
                line-height: 1;
                overflow: visible;
            }
        }

        #editor-container {
            min-height: 500px;
            margin-top: 20px;
        }

        #setup-container {
            padding: 20px 0;
            border-top: 1px solid #e8e8e8;

            .upload-area {
                display: flex;
                margin-top: 10px;
                padding: 10px;
            }

            .cover-uploader .avatar {
                width: 150px;
                height: 150px;
                display: block;
            }

            .cover-uploader {
                margin-left: 40px;
            }
        }
    }
}
</style>

<style lang="scss">
.cover-uploader .el-upload {
    border: 1px dashed #999;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.cover-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.cover-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
}
</style>